<?php

namespace common\observer;

use common\model\TaskMemberModel;
use common\model\TaskModel;
use common\model\UserModel;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 任务分执行人发生变化 添加task_member记录
 */
class TaskExecutorChangeSyncTaskMemberStatus implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['executor'])) {
            return;
        }
        $task = $subject->getSubjectData();

        if (empty($task['entity_id'])
            || $task['step_type'] != TaskModel::STEP_TYPE_STEP
            || !in_array($task['executor_type'], [TaskModel::EXECUTOR_TYPE_INSIDE, TaskModel::EXECUTOR_TYPE_DEFAULT])) {
            return;
        }
        $taskMemberList = model(TaskMemberModel::class)->where(['task_id' => $task['id']])->select();
        if ($updateData['executor'] > 0) {
            $executor = model(UserModel::class)->find($updateData['executor']);
            $hasExecutor = false;
            foreach ($taskMemberList as $taskMember) {
                if ($taskMember['partner'] != $executor['id']) {
                    model(TaskMemberModel::class)->delete($taskMember['id']);
                } else {
                    $hasExecutor = true;
                }
            }
            if (!$hasExecutor) {
                $taskJson = json_decode($task['json'], true);
                model(TaskMemberModel::class)->addItem([
                    'task_id' => $task['id'],
                    'user_id' => $executor['id'],
                    'partner' => $executor['id'],
                    'status' => $taskJson['task_status'] ?? 1,
                ]);
            }

        } else {
            if (!empty($taskMemberList)) {
                model(TaskMemberModel::class)->where(['id' => ['IN', array_column($taskMemberList, 'id')]])->delete();
            }
        }
    }

}
